package com.jdy.haoduoai.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.jdy.haoduoai.model.LeBanner;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.ViewPager;
import com.jdy.haoduoai.view.ViewPager.OnPageChangeListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

public class BannerAdapter extends PagerAdapter implements OnPageChangeListener {
  public static final int MAX_SIZE = 5000;
  public static final int FACTOR = 100;

  private final Context context;
  private final ViewPager mHost;
  private LinearLayout mLayoutNotifys;

  public DisplayImageOptions options;

  private final Handler handler = new Handler();
  private OnImageLoadedListener onImageLoadedListener;

  public BannerAdapter(Context context, ViewPager host) {
    super();
    this.context = context;
    this.mHost = host;
    mHost.setOnPageChangeListener(this);

    options = new DisplayImageOptions.Builder()
        .showImageOnFail(R.drawable.default_banner).cacheInMemory(true) // 缓存
        .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
        .build();
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
        context).writeDebugLogs().build();
    ImageLoader.getInstance().init(configuration);
  }

  private final ArrayList<LeBanner> mData = new ArrayList<LeBanner>();

  public void setData(List<LeBanner> data) {
    this.mData.clear();
    this.mData.addAll(data);

    if (mLayoutNotifys.getChildCount() != data.size()) {
      mLayoutNotifys.removeAllViews();
      for (int i = 0; i < mData.size(); i++) {

        ImageView notify = new ImageView(context);
        int size = Tools.getPixelByDip(context, 10);
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(size,
            size);
        param.rightMargin = 2 * Tools.getPixelByDip(context, 4);
        notify.setLayoutParams(param);
        notify.setScaleType(ScaleType.FIT_XY);
        notify.setImageResource(R.drawable.banner_dot1);
        mLayoutNotifys.addView(notify);
      }
    }

    notifyDataSetChanged();
    mHost.setCurrentItem(0);
  }

  public void setNotifyLayout(LinearLayout view) {
    this.mLayoutNotifys = view;
  }

  public ArrayList<LeBanner> getData() {
    return mData;
  }

  public int getDataSize() {
    return mData.size();
  }

  @Override
  public int getCount() {
    if (mData.size() <= 1) {
      return mData.size();
    } else {
      return MAX_SIZE;
    }
  }

  @Override
  public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == arg1;
  }

  // private class ViewHolder {
  // public ImageView image;
  // }

  HashMap<String, ImageView> viewCache = new HashMap<String, ImageView>();

  // HashMap<String, SoftReference<Bitmap>> bitmapCache = new HashMap<>();

  @Override
  public void setPrimaryItem(ViewGroup container, int position, Object object) {

    super.setPrimaryItem(container, position, object);

    // if (position >= mData.size()) {
    // return;
    // }
    //
    // final Banner banner = mData.get(position);
    // String imageUrl = banner.getImgUrl();
    // ImageView imageView = viewCache.get(banner.getImgUrl());
    // if (imageView == null) {
    // imageView = new ImageView(context);
    // imageView.setScaleType(ScaleType.FIT_XY);
    // viewCache.put(imageUrl, imageView);
    // }
    // refreshImage(imageView, position);
  }

  private void refreshImage(final ImageView imageView, final int position) {
    final LeBanner banner = mData.get(position);
    if (banner != null && !TextUtils.isEmpty(banner.banner_url)) {
      try {
        Picasso.with(context)
            .load(/* HttpUtils.HOST_RESOURCE + */banner.banner_url)
            .transform(new Transformation() {

              @Override
              public Bitmap transform(Bitmap bitmap) {
                Bitmap newbmp = null;
                if (bitmap != null) {
                  int width = context.getResources().getDisplayMetrics().widthPixels;
                  int w = bitmap.getWidth();
                  int h = bitmap.getHeight();

                  Log.e("flyinghf", "position == " + position + "|||" + "w == "
                      + w + " ||| h == " + h);

                  float scale = (float) width / w;
                  int height = (int) (h * scale);
                  try {
                    // String imageUrl = banner.getImgUrl();
                    newbmp = Bitmap.createScaledBitmap(bitmap, width, height,
                        false);
                    bitmap.recycle();
                    // SoftReference<Bitmap> refBitmap = new
                    // SoftReference<Bitmap>(newbmp);
                    // bitmapCache.put(imageUrl, refBitmap);
                    // imageView.setImageBitmap(newbmp);
                    ((View) mHost.getParent()).getLayoutParams().height = height;
                    // imageView.requestLayout();
                    // if (bitmap != newbmp) {
                    // bitmap.recycle();
                    // }
                  } catch (Exception e) {
                    // TODO: handle exception
                  } catch (Error e) {
                  }

                }
                handler.post(new Runnable() {

                  @Override
                  public void run() {
                    if (onImageLoadedListener != null) {
                      onImageLoadedListener.onLoaded();
                    }
                  }
                });

                return newbmp;
              }

              @Override
              public String key() {
                return ((View) mHost.getParent()).hashCode() + "BannerAdapter";
              }

            }).into(imageView, new Callback() {

              @Override
              public void onSuccess() {

              }

              @Override
              public void onError() {
                ImageLoader.getInstance().displayImage(banner.banner_url,
                    imageView, options);
              }
            });
      } catch (NullPointerException e) {
        ImageLoader.getInstance().displayImage(banner.banner_url, imageView,
            options);
      }

      return;
    }
    // Bitmap cache = null;
    // if (bitmapCache.get(banner.getImgUrl()) != null &&
    // bitmapCache.get(banner.getImgUrl()).get() != null) {
    // cache = bitmapCache.get(banner.getImgUrl()).get();
    // }
    // if (cache != null) {
    // imageView.setImageBitmap(cache);
    // } else {
    // ImageManager.getImage(banner.getImgUrl(), new RequestImageListener() {
    //
    // @Override
    // public void onRecievedImage(Bitmap bitmap) {
    //
    // if (bitmap != null) {
    // int width = context.getResources().getDisplayMetrics().widthPixels;
    // int w = bitmap.getWidth();
    // int h = bitmap.getHeight();
    // float scale = ((float) width / w);
    // int height = (int) (h * scale);
    // try {
    // String imageUrl = banner.getImgUrl();
    // Bitmap newbmp = Bitmap.createScaledBitmap(bitmap, width, height, false);
    // SoftReference<Bitmap> refBitmap = new SoftReference<Bitmap>(newbmp);
    // bitmapCache.put(imageUrl, refBitmap);
    // imageView.setImageBitmap(newbmp);
    // ((View) mHost).getLayoutParams().height = height;
    // imageView.requestLayout();
    // if (onImageLoadedListener != null) {
    // onImageLoadedListener.onLoaded();
    // }
    // } catch (Exception e) {
    // // TODO: handle exception
    // } catch (Error e) {
    // }
    //
    // }
    //
    // }
    //
    // @Override
    // public void onProgress(int progress) {
    //
    //
    // }
    // });
    // }

  }

  @Override
  public Object instantiateItem(ViewGroup container, final int pos) {

    final int position = pos % mData.size();
    final LeBanner banner = mData.get(position);
    ImageView imageView = viewCache.get(banner.banner_url);
    if (imageView == null) {
      imageView = new ImageView(context);
      imageView.setScaleType(ScaleType.FIT_XY);
      // viewCache.put(imageUrl, imageView);
    }

    refreshImage(imageView, position);
    ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(-1, -2);
    try {
      container.removeView(imageView);
    } catch (Exception e) {
      // TODO: handle exception
    }
    container.addView(imageView, param);

    imageView.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        if (mOnBannerClickListener != null) {
          mOnBannerClickListener.onBannerClicked(banner);
        }
      }
    });
    // return view;
    return imageView;
  }

  public interface OnBannerClickListener {
    public void onBannerClicked(LeBanner banner);
  }

  private OnBannerClickListener mOnBannerClickListener;

  public OnBannerClickListener getOnBannerClickListener() {
    return mOnBannerClickListener;
  }

  public void setOnBannerClickListener(
      OnBannerClickListener mOnBannerClickListener) {
    this.mOnBannerClickListener = mOnBannerClickListener;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
    if (object != null) {
      container.removeView((View) object);
    }
  }

  @Override
  public void onPageScrolled(int position, float positionOffset,
      int positionOffsetPixels) {

  }

  @Override
  public void onPageSelected(int position) {
    int count = mLayoutNotifys.getChildCount();
    int realPosition = position % count;
    setSelected(realPosition);
    if (count > 1) {
      if (position == MAX_SIZE - 1 || position == 0) {
        mHost.setCurrentItem(count * FACTOR + realPosition, false);
      }
    }
  }

  private void setSelected(int position) {
    for (int i = 0; i < mLayoutNotifys.getChildCount(); i++) {
      int res = R.drawable.banner_dot1;
      if (i == position) {
        res = R.drawable.banner_dot_s1;
      }
      ImageView img = (ImageView) mLayoutNotifys.getChildAt(i);
      img.setImageResource(res);
      img.invalidate();
    }
  }

  @Override
  public void onPageScrollStateChanged(int state) {

  }

  /**
   * 
   * 广告图片下载完成后的监听
   * 
   */
  public interface OnImageLoadedListener {
    void onLoaded();
  }

  public void setOnImageLoadedListener(
      OnImageLoadedListener onImageLoadedListener) {
    this.onImageLoadedListener = onImageLoadedListener;
  }

}
